package cn.com.domain;

import cn.com.Util.StringUtil;

/**
 * 定义区块链的类Block
 */
public class BlockEntity {

    public String hash;
    public String previousHash;
    //our data will be a simple message.
    private String data;
    //as number of milliseconds since 1/1/1970.
    private long timeStamp;
    private int nonce;

    //Block Constructor.
    //加密公文模块
    public BlockEntity(String data, String previousHash) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = System.currentTimeMillis();
        this.hash = calculateHash(); //Making sure we do this after we set the other values.
    }

    //Calculate new hash based on blocks contents
    //加密Hash值
    public String calculateHash() {
        return StringUtil.applySha256(
                previousHash +
                        Long.toString(timeStamp) +
                        Integer.toString(nonce) +
                        data
        );
    }

    //Increases nonce value until hash target is reached.
    public void mineBlock(int difficulty) {
        String target = StringUtil.getDificultyString(difficulty); //Create a string with difficulty * "0"
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!! : " + hash);
    }

}
